'''
toScreen 开源动画上位机
Author: ruxia-TJY
'''
from PySide6.QtWidgets import QApplication
from sys import exit,argv
from requests import get as rget
import json
import webbrowser

import Fun as F
import Var as V

from ui_py.MainWindow import Uipy_MainWindow

def init():
    '''
    初始化函数
    '''
    try:
        # 从config.json文件中读取默认值，复制到Var.py文件中的变量
        with open('config.json','r',encoding='utf-8') as f:
            configJson = json.loads(f.read())

        V.checkUpdate = configJson['checkUpdate']
        V.supportExtension_Video = configJson['supportExtension']['Video']
        V.supportExtension_Image = configJson['supportExtension']['Image']
        configDefault = configJson['default']
        V.default['baud'] = configDefault['baud']
        V.default['tran-width'] = configDefault['tran-width']
        V.default['tran-height'] = configDefault['tran-height']
        V.default['th'] = configDefault['th']
        V.default['sub-area'] = configDefault['sub-area']
        V.default['video']['fps'] = configDefault['video']['fps']
        V.default['video']['fs'] = configDefault['video']['fs']
        V.default['video']['width'] = configDefault['video']['width']
        V.default['video']['height'] = configDefault['video']['height']
        V.default['image']['width'] = configDefault['image']['width']
        V.default['image']['height'] = configDefault['image']['height']
    except FileNotFoundError:
        F.msgbox('提示','配置文件 config.json 不存在！')

if __name__ == '__main__':
    toScreen = QApplication(argv)
    toScreen.setApplicationName('toScreen')
    toScreen.setApplicationVersion('0.0.1.0')
    init()
    # 更新检查
    # 尽在此处使用requests库，删除更新检查后可以删除对requests库的引用
    try:
        if V.checkUpdate:
            Release = 'https://gitee.com/ruxia-tjy/to-screen/releases'
            LastReleaseApi = 'https://gitee.com/api/v5/repos/ruxia-tjy/to-screen/releases/latest'
            rJson = rget(LastReleaseApi,timeout=2).json()
            if 'tag_name' in rJson.keys():
                wVer = [int(i) for i in rJson['tag_name'].split('.')]
                lVer = [int(i) for i in toScreen.applicationVersion().split('.')]
                if wVer > lVer:
                    rBtn = F.msgbox('更新',f'检测到最新的版本为：{rJson["tag_name"]}，\n更新说明：\n{rJson["body"]}\n','打开网址','不管他')
                    if rBtn == 'Y':
                        webbrowser.open(Release)
    except:pass

    uiMain = Uipy_MainWindow()
    uiMain.lbl_Player.setText(f'<html><head/><body><p><span style=" font-size:28pt;">toScreen</span></p><p><span style=" font-size:12pt;">v{toScreen.applicationVersion()}</span></p></body></html>')
    uiMain.show()

    exit(toScreen.exec())